import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-multiple-choice',
    templateUrl: './multiple-choice.component.html',
    styleUrls: ['./multiple-choice.component.less'],
})
export class MultipleChoiceComponent implements OnInit {
    checked = false;
    loading = false;
    indeterminate = false;
    listOfData: readonly any[] = [];
    listOfCurrentPageData: readonly any[] = [];
    setOfCheckedId = new Set<number>();
    constructor() {}

    updateCheckedSet(id: number, checked: boolean): void {
        if (checked) {
            this.setOfCheckedId.add(id);
        } else {
            this.setOfCheckedId.delete(id);
        }
    }

    onCurrentPageDataChange(listOfCurrentPageData: readonly any[]): void {
        this.listOfCurrentPageData = listOfCurrentPageData;
        this.refreshCheckedStatus();
    }

    refreshCheckedStatus(): void {
        const listOfEnabledData = this.listOfCurrentPageData.filter(
            ({ disabled }) => !disabled
        );
        this.checked = listOfEnabledData.every(({ id }) =>
            this.setOfCheckedId.has(id)
        );
        this.indeterminate =
            listOfEnabledData.some(({ id }) => this.setOfCheckedId.has(id)) &&
            !this.checked;
    }

    onItemChecked(id: number, checked: boolean): void {
        this.updateCheckedSet(id, checked);
        this.refreshCheckedStatus();
    }

    onAllChecked(checked: boolean): void {
        this.listOfCurrentPageData
            .filter(({ disabled }) => !disabled)
            .forEach(({ id }) => this.updateCheckedSet(id, checked));
        this.refreshCheckedStatus();
    }

    sendRequest(): void {
        this.loading = true;
        const requestData = this.listOfData.filter((data) =>
            this.setOfCheckedId.has(data.id)
        );
        console.log(requestData);
        setTimeout(() => {
            this.setOfCheckedId.clear();
            this.refreshCheckedStatus();
            this.loading = false;
        }, 1000);
    }

    ngOnInit(): void {
        this.listOfData = new Array(100).fill(0).map((_, index) => ({
            id: index,
            name: `Edward King ${index}`,
            age: 32,
            address: `London, Park Lane no. ${index}`,
        }));
    }
}
